// 视频回忆页面功能
document.addEventListener('DOMContentLoaded', function() {
    // 加载数据
    loadJSON('data/content.json').then(data => {
        if (data) {
            // 渲染视频列表
            if (data.videos && data.videos.length > 0) {
                renderVideoTickets(data.videos);
                loadVideo(data.videos[0]); // 加载第一个视频
            }
            
            // 渲染照片墙
            if (data.photos && data.photos.length > 0) {
                renderPhotos(data.photos);
            }
            
            // 初始化爆米花效果
            initPopcornEffect();
        }
    });
    
    // 初始化照片查看器
    initPhotoViewer();
});

// 渲染视频票
function renderVideoTickets(videos) {
    const container = document.getElementById('video-selector');
    if (!container) return;
    
    videos.forEach((video, index) => {
        const ticket = document.createElement('div');
        ticket.className = `video-ticket ${index === 0 ? 'active' : ''}`;
        ticket.dataset.id = video.id;
        
        ticket.innerHTML = `
            <img src="${video.thumbnail}" alt="${video.title}" class="ticket-thumbnail">
            <div class="ticket-info">
                <div class="ticket-title">${video.title}</div>
                <div class="ticket-duration"><i class="fa fa-clock-o mr-1"></i>${video.duration}</div>
            </div>
        `;
        
        // 点击事件
        ticket.addEventListener('click', function() {
            // 更新活跃状态
            document.querySelectorAll('.video-ticket').forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            // 查找并加载对应的视频
            const videoToLoad = videos.find(v => v.id === parseInt(this.dataset.id));
            if (videoToLoad) {
                loadVideo(videoToLoad);
                playSound('audio/select.mp3');
            }
        });
        
        container.appendChild(ticket);
    });
}

// 加载视频
function loadVideo(video) {
    const videoElement = document.getElementById('main-video');
    const videoTitle = document.getElementById('video-title');
    const videoDescription = document.getElementById('video-description');
    
    if (!videoElement || !videoTitle || !videoDescription) return;
    
    // 更新视频源
    videoElement.src = video.url;
    videoElement.load();
    videoElement.play().catch(e => console.log('视频自动播放失败:', e));
    
    // 更新视频信息
    videoTitle.textContent = video.title;
    videoDescription.textContent = video.description;
}

// 渲染照片墙
function renderPhotos(photos) {
    const container = document.getElementById('photos-grid');
    if (!container) return;
    
    photos.forEach(photo => {
        const card = document.createElement('div');
        card.className = 'photo-card';
        card.dataset.id = photo.id;
        
        card.innerHTML = `
            <img src="${photo.url}" alt="${photo.title}">
            <div class="photo-overlay">
                <div class="photo-title">${photo.title}</div>
                <div class="photo-description">${photo.description}</div>
            </div>
        `;
        
        // 点击查看大图
        card.addEventListener('click', function() {
            openPhotoViewer(photos.find(p => p.id === parseInt(this.dataset.id)));
        });
        
        container.appendChild(card);
    });
}

// 初始化照片查看器
function initPhotoViewer() {
    const viewer = document.getElementById('photo-viewer');
    const viewerImage = document.getElementById('viewer-image');
    const viewerTitle = document.getElementById('viewer-title');
    const viewerDescription = document.getElementById('viewer-description');
    const closeButton = document.getElementById('viewer-close');
    
    if (!viewer || !viewerImage || !closeButton) return;
    
    // 关闭查看器
    function closeViewer() {
        viewer.classList.remove('active');
        document.body.style.overflow = ''; // 恢复滚动
    }
    
    // 关闭按钮事件
    closeButton.addEventListener('click', closeViewer);
    
    // 点击外部关闭
    viewer.addEventListener('click', function(e) {
        if (e.target === this) {
            closeViewer();
        }
    });
    
    // ESC键关闭
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && viewer.classList.contains('active')) {
            closeViewer();
        }
    });
    
    // 暴露打开查看器的函数
    window.openPhotoViewer = function(photo) {
        if (!photo) return;
        
        viewerImage.src = photo.url;
        viewerImage.alt = photo.title;
        
        if (viewerTitle) viewerTitle.textContent = photo.title;
        if (viewerDescription) viewerDescription.textContent = photo.description;
        
        viewer.classList.add('active');
        document.body.style.overflow = 'hidden'; // 禁止滚动
    };
}

// 初始化爆米花效果
function initPopcornEffect() {
    const container = document.getElementById('popcorn-container');
    const videoElement = document.getElementById('main-video');
    
    if (!container || !videoElement) return;
    
    // 创建爆米花
    function createPopcorn() {
        if (videoElement.paused) return;
        
        const popcorn = document.createElement('div');
        popcorn.className = 'popcorn';
        
        // 随机位置（视频上方）
        const left = Math.random() * 80 + 10; // 10% - 90%
        popcorn.style.left = `${left}%`;
        popcorn.style.top = '-10px';
        
        // 随机动画
        const duration = Math.random() * 4 + 3;
        const rotate = Math.random() * 360;
        const translateX = (Math.random() * 100) - 50; // -50px 到 50px
        
        popcorn.style.animation = `
            ${duration}s linear forwards
        `;
        
        // 动画帧
        let start = null;
        function animate(timestamp) {
            if (!start) start = timestamp;
            const progress = (timestamp - start) / (duration * 1000);
            
            if (progress < 1) {
                // 抛物线运动
                const y = 300 * progress; // 垂直下落
                const x = translateX * Math.sin(progress * Math.PI); // 水平摆动
                
                popcorn.style.transform = `translate(${x}px, ${y}px) rotate(${rotate + progress * 360}deg)`;
                popcorn.style.opacity = 1 - progress;
                
                requestAnimationFrame(animate);
            } else {
                // 动画结束，移除元素
                if (container.contains(popcorn)) {
                    container.removeChild(popcorn);
                }
            }
        }
        
        container.appendChild(popcorn);
        requestAnimationFrame(animate);
    }
    
    // 视频播放时定期创建爆米花
    let popcornInterval;
    
    videoElement.addEventListener('play', function() {
        // 每500ms创建一个爆米花
        popcornInterval = setInterval(createPopcorn, 500);
    });
    
    videoElement.addEventListener('pause', function() {
        clearInterval(popcornInterval);
    });
    
    videoElement.addEventListener('ended', function() {
        clearInterval(popcornInterval);
        // 播放结束，显示掌声效果
        playSound('audio/applause.mp3');
    });
}

// 播放音效
function playSound(url) {
    const audio = new Audio(url);
    audio.volume = 0.5;
    audio.play().catch(e => console.log('播放音效失败:', e));
}
